﻿
/*************************************************
Author : Bill
Create : 2011-06-02
Remark : Map ABC Interface ----- Flash Version
*************************************************/
Array.prototype.clear = function() { this.length = 0; };

var MEnumMapToolType = {
    Pan: 0,
    DrawRectangleGeoFence: 1,
    DrawCircleGeoFence: 2,
    DrawPolyLine: 3,
    DrawPolyGon: 4,
    AddPOI: 5,
    BeginEditMovePOI: 6,
    EndEditMovePOI: 7,
    DrawDefinedRouteLine:8
};

var MSMMap = function(mmap) {
    var msmMap = this;
    this.map = mmap;
    this.mapTool = MEnumMapToolType.Pan;
    this.historyshowindex = 0;
    this.historyshowtimer = null;
    this.historyLine = null;
    this.FnGeoFenceCallBack = null;
    this.FnCircleGeoFenceCallBack = null;
    this.map.containerClass = this;
    this.firstTimeLoad = true;
    this.allDeviceOverlay = new Array();
    this.trackerinfoLastArray = new Array();
    this.vehicleOverlayerArray = new Array();
    this.historyOverlayArray = new Array();
    this.trackerhistoryinfoArray = new Array();
    this.historyRecapPoints = new Array();
    this.poiOverlayArray = new Array();
    this.mySearchRouteOverlay = new Array();
    this.geocoder = new MReGeoCodeSearch(); //逆地理编码
    this.animateinterval = 2; //历史轨迹播放速度等级
    this.stopanimate = false;
    this.findOutLocationOverlay = null;
    this.theFirstHistoryPoint = null;
    this.theLastHistoryPoint = null;
    this.addPOIOverlay = null;
    this.movePOIOverlay = null;
    this.realtimeTrackingLine = null;
    this.realtimeOverlayArray = new Array();
    //部分标签
    this._parkingTimeCap = "";
    this._gpsTimeCap = "";
    this._speedCap = "";
    this._submitcap = "";
    this._cancelcap = "";
    this._submitAddRouteCap = "";
    this._submitAddAllRouteCap = "";
    this._cancelAddRouteCap = "";
    this._farCap = "";
    this._closeCap = "";
    //自定义路线变量
    this.allDefinedRoutePoint = new Array();
    this.simpleDefinedRoute = null;
    this.complecateDefinedRoute = null;
    this._isEditMode = false;
    this._editRouteID = null;
    this._historylineendfn = null;
    this._historyshowtimer = null;
    this._hidehistoryline = false;
    /***************************Map abc 地图事件*******************************
    ***************************************************************************/
    this.map.addEventListener(this.map, MConstants.ADD_OVERLAY, function(params) {
        var overlay = msmMap.map.getOverlayById(params.overlayId);
        //绘制meitrack协议上电子报警
        if (msmMap.mapTool == MEnumMapToolType.DrawCircleGeoFence && overlay.TYPE == "Circle") {
            msmMap.changeTool(MEnumMapToolType.Pan);
            if (msmMap.FnCircleGeoFenceCallBack)
                msmMap.FnCircleGeoFenceCallBack(overlay.center.latY, overlay.center.lngX, overlay.radius);
            msmMap.map.removeOverlay(overlay);
        }
        //绘制meiligao协议上电子报警
        else if (msmMap.mapTool == MEnumMapToolType.DrawRectangleGeoFence && overlay.TYPE == "Rectangle") {
            msmMap.changeTool(MEnumMapToolType.Pan);
            if (msmMap.FnGeoFenceCallBack)
                msmMap.FnGeoFenceCallBack(overlay.lnglatArr[0].latY, overlay.lnglatArr[0].lngX, overlay.lnglatArr[1].latY, overlay.lnglatArr[1].lngX);
            msmMap.map.removeOverlay(overlay);
        }
        else if (params.overlayId == "myaddpoi" || params.overlayId == "mymovepoi") {
            msmMap.map.openOverlayTip(params.overlayId);
        }
    });

    this.map.addEventListener(this.map, MConstants.MOUSE_CLICK, function(params) {
        if (msmMap.mapTool == MEnumMapToolType.AddPOI) {
            msmMap.drawAddPOI(params.eventY, params.eventX, 0);
        }
        else if (msmMap.mapTool == MEnumMapToolType.BeginEditMovePOI) {
            msmMap.drawMovePOI(this._movepoiid, params.eventY, params.eventX, 0);
            msmMap.changeTool(MEnumMapToolType.Pan);
        }
        else if (msmMap.mapTool == MEnumMapToolType.DrawDefinedRouteLine) {
            if (msmMap.allDefinedRoutePoint.length > 1)
                return;
            var id = "my_defined_route_point_" + msmMap.allDefinedRoutePoint.length;
            var marker;
            marker = msmMap.createDefinedRouteStepMarker(id, new MLngLat(params.eventX, params.eventY), null, null, "images/mm_20_white.png", true);
            marker.index = msmMap.allDefinedRoutePoint.length;
            msmMap.map.addOverlay(marker, false);
            msmMap.allDefinedRoutePoint.push(marker);
            if (msmMap.allDefinedRoutePoint.length == 2) {
                var arr = new Array();
                for (var i = 0; i < msmMap.allDefinedRoutePoint.length; i++) {
                    arr.push(msmMap.allDefinedRoutePoint[i].lnglat);
                }
                msmMap.simpleDefinedRoute = msmMap.createMABCPolyLine("my_defined_simple_route", arr, MConstants.LINE_SOLID, 0x005cb5, true);
                msmMap.routeSearch(500, 0);
            }
        }
    });
    /****************************************************************************
    *****************************************************************************/
}

MSMMap.prototype = {
    checkResize: function() {
    },

    mapLatLngToRealLatLng: function(pt) {
        return unreviseMapLatLng(pt);
    },

    realLatLngToMapLatLng: function(pt) {
        return reviseRealLatLngToMap(pt);
    },

    createMABCMarker: function(id, pt, labelOption, tipOption, imgsrc, isEditable, place) {
        var absoluturl = window.location.href;
        var markerpath = absoluturl;
        if (window.location.host == "localhost") {
            markerpath = "http://gd.meiligao.cc/";
        }
        else {

            if (absoluturl.indexOf('.aspx') != -1) {
                //包含aspx
                var host = window.location.host;
                var folder = window.location.pathname;
                var f = new Array();
                f = folder.split("/");
                if (f.length > 2) {
                    markerpath = "http://" + host + "/" + f[1] + "/";
                }
                else {
                    markerpath = "http://" + host + "/";
                }
            }
            else {
                var host = window.location.host;
                var folder = window.location.pathname;
                var f = new Array();
                f = folder.split("/");
                if (f.length > 2) {
                    markerpath = "http://" + host + "/" + f[1] + "/";
                }
                else {
                    markerpath = "http://" + host + "/";
                }
            }
        }
        var myDomain = markerpath;
        var markerOption = new MMarkerOptions();
        //标注图片或SWF的url，默认为蓝色气球图片
        markerOption.imageUrl = myDomain + imgsrc;
        markerOption.picAgent = false;
        //图片锚点BOTTOM_CENTER相对于标注位置的位置
        markerOption.isEditable = isEditable;
        markerOption.isDimorphic = false;
        //设置图片相对于加点经纬度坐标的位置。九宫格位置。默认BOTTOM_CENTER代表正下方
        if (typeof (place) == 'undefined')
            markerOption.imageAlign = MConstants.BOTTOM_CENTER;
        else
            markerOption.imageAlign = place;
        //设置点的标注参数选项 
        markerOption.labelOption = labelOption;
        //是否在地图中显示信息窗口，true，可以显示（默认）；false，不显示
        markerOption.tipOption = tipOption;
        markerOption.canShowTip = tipOption != null ? true : false;
        //通过经纬度坐标及参数选项确定标注信息 
        var Mmarker = new MMarker(pt, markerOption);
        //对象编号，也是对象的唯一标识
        Mmarker.id = id;
        return Mmarker;
    },
    createEditableMarker: function(id, pt, labelOption, tipOption, imgsrc, isEditable, dragStartFn, draggingFn, dragEndFn, clickFn) {
        var marker = this.createMABCMarker(id, pt, labelOption, tipOption, imgsrc, isEditable);
        if (dragStartFn != null && dragStartFn != undefined) {
            this.map.addEventListener(marker, MConstants.DRAG_START, dragStartFn);
        }
        if (draggingFn != null && draggingFn != undefined) {
            this.map.addEventListener(marker, MConstants.DRAGGING, draggingFn);
        }
        if (dragEndFn != null && dragEndFn != undefined) {
            this.map.addEventListener(marker, MConstants.DRAG_END, dragEndFn);
        }
        if (clickFn != null && clickFn != undefined) {
            this.map.addEventListener(marker, MConstants.MOUSE_CLICK, clickFn);
        }
        return marker;
    },
    createDefinedRouteStepMarker: function(id, pt, labelOption, tipOption, imgsrc, isEditable) {
        var myClass = this;
        var marker = null;
        marker = myClass.createEditableMarker(id, pt, labelOption, tipOption, imgsrc, isEditable, function drag_start(params) {
        }, function dragging(params) {
        }, function dragg_end(params) {

            if (myClass.allDefinedRoutePoint.length == 2) {
                var arr = new Array();
                marker.lnglat.lngX = params.eventX;
                marker.lnglat.latY = params.eventY;
                for (var i = 0; i < myClass.allDefinedRoutePoint.length; i++) {
                    arr.push(myClass.allDefinedRoutePoint[i].lnglat);
                }
                myClass.simpleDefinedRoute = myClass.createMABCPolyLine("my_defined_simple_route", arr, MConstants.LINE_SOLID, 0x005cb5, true);
                myClass.routeSearch(500, 0);
            }
        }, function() {
            var pointsString = "";
            var poly = myClass.complecateDefinedRoute;
            for (var i = 0; i < poly.lnglatArr.length; i++) {
                var p = poly.lnglatArr[i];
                p = myClass.mapLatLngToRealLatLng(p);
                if (i == 0) {
                    pointsString = p.lngX + "," + p.latY;
                }
                else {
                    pointsString += "|" + p.lngX + "," + p.latY;
                }
            }

            var WIN_HTML = '<div style="width: 12em; style: font-size: small"><INPUT id="my_route_line" value=""/><br/><INPUT class="cornerbutton" type="button" value="';
            WIN_HTML += myClass._submitAddRouteCap + '"   onclick="submitAddRouteEvent(\'' + pointsString.toString() + '\',false,\'' + myClass._editRouteID + '\');"/>&nbsp;<INPUT class="cornerbutton" type="button" value="';
            WIN_HTML += myClass._submitAddAllRouteCap + '"  onclick="submitAddRouteEvent(\'' + pointsString.toString() + '\',true);"/>&nbsp;<INPUT  type="button" value="';
            WIN_HTML += myClass._cancelAddRouteCap + '"  class="cornerbutton"  onclick="cancelAddRouteEvent()"/>&nbsp;</div>';
            var tipOption = new MTipOptions();
            tipOption.tipType = MConstants.IMG_BUBBLE_TIP;
            tipOption.content = WIN_HTML;
            marker.option.tipOption = tipOption;
            marker.option.canShowTip = true;
            myClass.map.updateOverlay(marker);
            myClass.map.openOverlayTip(marker.id);
        });
        marker.index = myClass.allDefinedRoutePoint.length;
        return marker;
    },
    createMABCPolyLine: function(id, pts, lineType, lineColor, isEditable) {
        var linestyle = new MLineStyle(); //创建线样式对象 
        linestyle.thickness = 3; //线的粗细度，默认为2
        linestyle.color = lineColor; //线的颜色，16进制整数，默认为0x005890（蓝色）
        linestyle.lineType = lineType; //线的表现样式，LINE_SOLID，实线（默认），LINE_DASHED，虚线

        var lineopt = new MLineOptions(); //构造一个名为lineopt的线选项对象
        lineopt.lineStyle = linestyle; //设置线的边缘风格 
        lineopt.canShowTip = false; //设置是否在地图中显示信息窗口，true，可显示（默认）；false，不显示
        lineopt.isEditable = isEditable; //设置线是否为可编辑状态，true，可编辑；false，不可编辑（默认） 
        lineopt.isDimorphic = true; //设置线是否高亮显示，默认为false,即没有高亮显示；true，有高亮显示 
        lineopt.dimorphicColor = 0x00A0FF; //设置第二种状态的颜色，默认为0xFF0000，即红色
        var polyline = new MPolyline(pts, lineopt); //通过经纬度坐标数组及参数选项构建多折线对象，arr是经纬度坐档数组
        polyline.id = id; //对象编号，也是对象的唯一标识 
        return polyline;
    },
    changeTool: function(toolType) {
        this.mapTool = toolType;
        switch (toolType) {
            case MEnumMapToolType.Pan:
                this.map.setCurrentMouseTool(MConstants.PAN_WHEELZOOM);
                break;
            case MEnumMapToolType.DrawCircleGeoFence:
                this.map.setCurrentMouseTool(MConstants.DRAW_CIRCLE);
                break;
            case MEnumMapToolType.DrawRectangleGeoFence:
                this.map.setCurrentMouseTool(MConstants.DRAW_RECTANGLE);
                break;
            case MEnumMapToolType.DrawLine:
                this.map.setCurrentMouseTool(MConstants.DRAW_LINE);
                break;
            case MEnumMapToolType.DrawPolyGon:
                this.map.setCurrentMouseTool(MConstants.DRAW_POLYGON);
                break;
        }
    },
    setCenterAndZoom: function(lngX, latY, zoomLevel) {
        this.map.setZoomAndCenter(zoomLevel, new MLngLat(lngX, latY));
    },

    drawFromStore: function(pstore, bolCenter, zoomLevel) {
        this.allDeviceOverlay = [];
        var count = pstore.getCount();
        var i;
        var lasttinfo = null;
        for (i = 0; i < count; i++) {
            var record = pstore.getAt(i);
            var tinfo = this.translateRecordToTrackerInfo(record);
            this.allDeviceOverlay.push(tinfo);
            lasttinfo = tinfo;
        }
        this.showNewTrackerInfoOnMap();
        if (bolCenter && (lasttinfo != null)) {
            if (lasttinfo.gsminfo)
                this.setCenterbyLatLng(lasttinfo.gsminfo.longitude, lasttinfo.gsminfo.latitude);
            else
                this.setCenterbyLatLng(lasttinfo.longitude, lasttinfo.latitude);
        }
    },

    showNewTrackerInfoOnMap: function() {
        var tinfoArr = new Array();
        for (var i = 0; i < this.allDeviceOverlay.length; i++) {
            var tinfo = this.allDeviceOverlay[i];
            var pt = tinfo.gsminfo != null ? pt = new MLngLat(tinfo.gsminfo.longitude, tinfo.gsminfo.latitude) : new MLngLat(tinfo.longitude, tinfo.latitude);
            pt = this.realLatLngToMapLatLng(pt);
            tinfo.setMarker(this.createMarker(pt, tinfo));
            tinfoArr.push(tinfo);
        }
        this.drawNewTrackerInfo(tinfoArr);
    },

    drawNewTrackerInfo: function(trackerArr) {
        if (this.firstTimeLoad) {
            var overlays = new Array();
            for (var j = 0; j < trackerArr.length; j++) {
                overlays.push(trackerArr[j].marker);
                this.trackerinfoLastArray.push(trackerArr);
                this.vehicleOverlayerArray.push(trackerArr[j].marker);
                if (trackerArr[j].marker.gsmCircle != null) {
                    overlays.push(trackerArr[j].marker.gsmCircle);
                }

            }
            var myClass = this;
            setTimeout(function() {
                myClass.map.addOverlays(overlays, true);
            }, 2500);
            this.firstTimeLoad = false;
        }
        else {
            for (var j = 0; j < trackerArr.length; j++) {
                var i;
                var alreadyhas = false;
                var index = -1;
                for (i = 0; i < this.trackerinfoLastArray.length; i++) {
                    var tmptrackerinfo = this.trackerinfoLastArray[i];
                    if (tmptrackerinfo.deviceid == trackerArr[j].deviceid) {
                        this.map.removeOverlay(trackerArr[j].marker);
                        if (tmptrackerinfo.marker.gsmCircle)
                            this.map.removeOverlay(tmptrackerinfo.marker.gsmCircle);
                        this.vehicleOverlayerArray.remove(tmptrackerinfo.marker);
                        index = i;
                        alreadyhas = true;
                        break;
                    }
                }
                if (alreadyhas) {
                    delete this.trackerinfoLastArray[index].marker;
                    this.trackerinfoLastArray.remove(this.trackerinfoLastArray[index]);
                }
                if (trackerArr[j].marker.gsmCircle != null) {
                    this.map.addOverlays([trackerArr[j].marker.gsmCircle, trackerArr[j].marker], false);
                }
                else {
                    this.map.addOverlay(trackerArr[j].marker, false);
                }
                this.vehicleOverlayerArray.push(trackerArr[j].marker);
                this.trackerinfoLastArray.push(trackerArr[j]);
            }
        }
    },
    createCircle: function(pt, radius, color) {
        var arr = new Array();
        arr.push(pt);
        var linestyle = new MLineStyle(); //创建线样式对象 
        linestyle.thickness = 3; //线的粗细度，默认为2
        linestyle.color = color; //线的颜色，16进制整数，默认为0x005890（蓝色） 
        var fillstyle = new MFillStyle(); //创建填充样式对象
        fillstyle.color = color; //面的填充颜色，16进制整数。 
        fillstyle.alpha = 0.5; //填充面的透明度，范围0~1，0为透明，1为不透明（默认） 
        var areastyle = new MAreaStyle(); //创建面样式对象 
        areastyle.borderStyle = linestyle; //面的边框风格。 
        areastyle.fillStyle = fillstyle; //面的填充风格。 
        var areaopt = new MAreaOptions(); //构建一个名为areopt的面选项对象。
        areaopt.areaStyle = areastyle; //设置面的风格
        areaopt.canShowTip = false;
        return new MCircle(arr, radius, areaopt); //利用圆的中心点、圆半径及option选项来创建圆对象 
    },
    createMarker: function(pt, trackerinfo) {
        var direction = parseFloat(trackerinfo.direction);
        var speedkmh = parseInt(trackerinfo.speed);
        var circle = null;
        if (trackerinfo.gsminfo != null) {
            circle = this.createCircle(pt, trackerinfo.gsminfo.accuracy / 2, '0x0000ff', false);
            circle.id = trackerinfo.deviceid + '-circle';
        }
        var s = trackerinfo.devicetype;
        var imgsrc = trackerinfo.iconname != "" ? "images/trackericon/" + trackerinfo.iconname + "_" : "images/" + this.getDefaultImageUrl(trackerinfo);
        if (trackerinfo.iconname != "") {
            if (direction >= 337.5 || direction < 22.5)
                imgsrc += "n.png";
            else if (direction >= 22.5 && direction < 67.5)
                imgsrc += "ne.png";
            else if (direction >= 67.5 && direction < 112.5)
                imgsrc += "e.png";
            else if (direction >= 112.5 && direction < 157.5)
                imgsrc += "se.png";
            else if (direction >= 157.5 && direction < 202.5)
                imgsrc += "s.png";
            else if (direction >= 202.5 && direction < 247.5)
                imgsrc += "sw.png";
            else if (direction >= 247.5 && direction < 292.5)
                imgsrc += "w.png";
            else if (direction >= 292.5 && direction < 337.5)
                imgsrc += "nw.png";
        }
        //标签风格
        var labelOption = new MLabelOptions();
        labelOption.hasBorder = true;
        labelOption.hasBackground = true;
        labelOption.labelPosition = new MPoint(16, -16);
        labelOption.alpha = 0.8;
        labelOption.content = trackerinfo.devicename + ' ' + trackerinfo.speed + 'km/h' + ' ' + (hasEmergencyAlarm(trackerinfo.alarminfo) ? getAlarmStringFromAlarmType(trackerinfo.alarminfo) : '') + ' ' + trackerinfo.gpstime;
        var alarmInfo = (hasEmergencyAlarm(trackerinfo.alarminfo) ? getAlarmStringFromAlarmType(trackerinfo.alarminfo) : '');
        if (alarmInfo.length > 0) {
            labelOption.fontStyle.color = 0xFF0000;
        }
        var Mmarker = this.createMABCMarker(trackerinfo.deviceid, pt, labelOption, null, imgsrc, false, MConstants.MIDDLE_CENTER);
        Mmarker.gsmCircle = circle;
        return Mmarker;

    },
    createTrackMarker: function(id, point, directionString, win_html) {
        var direction = parseFloat(directionString);
        var baseImagePath = "images/blue_";
        //tmarker.id = Math.random().toString();
        if (direction >= 337.5 || direction < 22.5)
            baseImagePath += "n.png";
        else if (direction >= 22.5 && direction < 67.5)
            baseImagePath += "ne.png";
        else if (direction >= 67.5 && direction < 112.5)
            baseImagePath += "e.png";
        else if (direction >= 112.5 && direction < 157.5)
            baseImagePath += "se.png";
        else if (direction >= 157.5 && direction < 202.5)
            baseImagePath += "s.png";
        else if (direction >= 202.5 && direction < 247.5)
            baseImagePath += "sw.png";
        else if (direction >= 247.5 && direction < 292.5)
            baseImagePath += "w.png";
        else if (direction >= 292.5 && direction < 337.5)
            baseImagePath += "nw.png";
        var tipOption = new MTipOptions();
        tipOption.content = win_html != undefined ? win_html : "";
        var trackerMarker = this.createMABCMarker(id, point, null, tipOption, baseImagePath);
        trackerMarker.option.canShowTip = (trackerMarker.option.tipOption.content == "") ? false : true;
        this.map.updateOverlay(trackerMarker);
        var myClass = this;
        this.map.addEventListener(trackerMarker, MConstants.MOUSE_CLICK, function() {
            myClass.geoCoder(point.latY, point.lngX, function(address, value) {
                if (trackerMarker.option.canShowTip == false) {
                    trackerMarker.option.tipOption.content = (win_html != undefined ? win_html : "") + address;
                    trackerMarker.option.canShowTip = true;
                    myClass.map.updateOverlay(trackerMarker);
                    myClass.map.openOverlayTip(trackerMarker.id);
                }
            });
        });
        return trackerMarker;
    },
    createStoppedMarker: function(id, point, win_html) {
        var myClass = this;
        var marker = this.createMABCMarker(id, point, null, null, "images/red-stop.png");
        this.map.addEventListener(marker, MConstants.MOUSE_CLICK, function() {
            myClass.geoCoder(point.latY, point.lngX, function(address, value) {
                var tipOption = new MTipOptions();
                tipOption.content = win_html == undefined ? address : win_html + address;
                myClass.map.openTip(new MLngLat(point.lngX, point.latY), tipOption);
            });
        });
        return marker;
    },
    createTrackBeginEndMarker: function(id, point, begin, win_html) {
        var myClass = this;
        var img;
        if (begin)
            img = "images/icon_greenA.png";
        else
            img = "images/icon_greenB.png";
        var marker = this.createMABCMarker(id, point, null, null, img);
        this.map.addEventListener(marker, MConstants.MOUSE_CLICK, function() {
            myClass.geoCoder(point.latY, point.lngX, function(address, value) {
                var tipOption = new MTipOptions();
                tipOption.content = win_html == undefined ? address : win_html + address;
                myClass.map.openTip(new MLngLat(point.lngX, point.latY), tipOption);
            });
        });
        return marker;
    },
    translateRecordToTrackerInfo: function(record) {
        var sssid = record.get("sssid");
        var devicename = record.get("devicename");
        var devicetype = record.get("devicetype");
        var gpsavailable = record.get("gpsavailable");
        var latitude = record.get("latitude");
        var longitude = record.get("longitude");
        var gpstime = record.get("gpstime");
        var receivedtime = record.get("receivedtime");
        var direction = record.get("direction");
        var speed = record.get("speed");
        var altitude = record.get("altitude");
        var devicestate = record.get("devicestate");
        var address = record.get("address");
        var alarminfo = record.get("alarminfo");
        var baseid = record.get("baseid");
        var hasgsmlocation = record.get("hasgsmlocation");
        var gsmlatitude = record.get("gsmlatitude");
        var gsmlongitude = record.get("gsmlongitude");
        var gsmaccuracy = record.get("gsmaccuracy");
        var iconname = record.get("iconname");
        var alarmcustomText = record.get("alarmcustomText");
        var gsm = null;
        if (hasgsmlocation) {
            gsm = new GSMInfo(gsmlatitude, gsmlongitude, 0, gsmaccuracy, "");
        }
        var tinfo = new TrackerInfo(sssid, devicename, devicetype, gpsavailable, longitude, latitude, gpstime, receivedtime, direction, speed, altitude, devicestate, address, alarminfo, gsm, null, null, null, iconname, alarmcustomText);
        return tinfo;
    },
    geoCoder: function(lati, longi, fncallback, ismaplatlng) {

        var latlng = new MLngLat(longi, lati);
        latlng = this.realLatLngToMapLatLng(latlng);
        var opt = new MReGeoCodeSearchOptions();
        opt.poiNumber = 10; ; //返回周边的POI数量,默认10 
        opt.range = 3000; //限定周边热点POI和道路的距离范围
        opt.pattern = 0; //返回数据的模式,0表示返回地标性POI,1表示返回全部POI，

        this.geocoder.setCallbackFunction(function(data) {
            if (data.error_message != null) return;
            switch (data.message) {
                case 'ok':
                    var address = "";
                    var addressData = data.SpatialBean;
                    if (addressData.poiList.length > 1)
                        address = addressData.Province.name + addressData.City.name + addressData.District.name + addressData.poiList[0].address + "-" + addressData.poiList[0].name;
                    if (fncallback != null)
                        fncallback(address, 1);
                    break;
                case 'error':
                    if (fncallback != null)
                        fncallback("", 0);
                    break;
                default:
                    Ext.Ajax.request({
                        url: 'Handler/HandlerGetAddress',
                        method: 'post',
                        params: {
                            lat: lati,
                            lng: longi

                        },
                        success: function(r) {
                            var val = r.responseText;

                            if (fncallback != null)
                                fncallback(val, 0);
                        }
                    });

                    break;
            }
        });
        this.geocoder.poiToAddress(latlng, opt);
    },
    beginDrawGeoFence: function(inout) {
        this.changeTool(MEnumMapToolType.DrawRectangleGeoFence);
    },
    beginDrawCircleGeoFence: function(inout) {
        this.changeTool(MEnumMapToolType.DrawCircleGeoFence);
    },
    setCenterbyLatLng: function(lng, lat, zoom) {
        if (lat && lng) {
            var pt = new MLngLat(lng, lat); //--trans latlng-
            this.map.setCenter(pt);
        }
        if (zoom != null && zoom != undefined)
            this.map.setZoomLevel(zoom);

    },
    drawAnimateHistoryLine: function(extdatastore, gpsTimeCap, speedCap, fnShowEndCallback, hideLine) {
        this._historylineendfn = fnShowEndCallback;
        this._hidehistoryline = (typeof (hideLine) != 'undefined' ? hideLine : false);
        this._gpsTimeCap = gpsTimeCap;
        this._speedCap = speedCap;
        //        if (this.historyLine != null) {
        //            this.map.removeOverlay(this.historyLine);
        //            this.historyLine == null;
        //        }
        //        this.map.removeOverlays(this.historyOverlayArray);
        for (var i = 0; i < extdatastore.getCount(); i++) {
            var record = extdatastore.getAt(i);
            var lati = record.get("latitude");
            var longi = record.get("longitude");
            var otherLati = (i == extdatastore.getCount() - 1) ? parseFloat(extdatastore.getAt(i).get("latitude")) : parseFloat(extdatastore.getAt(i + 1).get("latitude"));
            var otherLongi = (i == extdatastore.getCount() - 1) ? parseFloat(extdatastore.getAt(i).get("longitude")) : parseFloat(extdatastore.getAt(i + 1).get("longitude"));
            var gpstime = record.get("gpstime");
            var direction = record.get("direction");
            var speed = record.get("speed");
            var otherinfo = record.get("otherinfo");
            var stopped = record.get("stopped");
            var stoppedtime = record.get("stoppedtime");
            var historyinfo = new TrackerInfo("", "", "", "", longi, lati, gpstime, "", direction, speed, "", "", "", "", "", otherinfo, stopped, stoppedtime);
            this.trackerhistoryinfoArray.push(historyinfo);
        }
        this.showAnimate();
    },

    showAnimate: function() {
        var pts = new Array();
        var myClass = this;
        if (myClass.historyshowindex < myClass.trackerhistoryinfoArray.length) {
            var vinfo = this.trackerhistoryinfoArray[myClass.historyshowindex];
            myClass.historyshowindex++;
            var myId = 'historymarker-' + vinfo.gpstime;
            var pt = new MLngLat(vinfo.longitude, vinfo.latitude);
            pt = this.realLatLngToMapLatLng(pt);
            var WIN_HTML;
            var timetext = this._gpsTimeCap + ':' + vinfo.gpstime + '<BR/>';
            var speedtext = this._speedCap + ':' + vinfo.speed + 'km/h<BR/>';
            var otherinfo = "";
            if (vinfo.otherinfo)
                otherinfo = vinfo.otherinfo + '<BR/>';
            WIN_HTML = timetext + speedtext + otherinfo;
            if (vinfo.stopped)
                WIN_HTML += this._parkingTimeCap + ":" + vinfo.stoppedtime + '<BR/>';
            var mm;
            if (vinfo.stopped) {
                mm = this.createStoppedMarker(myId, pt, WIN_HTML);
            }
            else
                mm = this.createTrackMarker(myId, pt, vinfo.direction.toString(), WIN_HTML);
            this.historyOverlayArray.push(mm);
            pts.push(pt);
        }
        var gpsMarker = this.createMABCMarker("historymarker", this.theFirstHistoryPoint, null, null, "images/history_recap_car.png");
        this.map.addOverlay(gpsMarker, true);
        if (!this._hidehistoryline) {
            historyLine = this.createMABCPolyLine("historyline", pts, MConstants.LINE_DASHED, 0x005cb5, false);

            this.map.addOverlay(historyLine, false);
        }
        var arr = new Array();
        arr.push("historymarker");
        this.map.setGPSFocus(MConstants.FOCUS, arr);
        this.map.markerMoveAlong("historymarker", pts, this.animateinterval);
        this.historyRecapPoints = pts;

        setTimeout(function() { myClass.map.startMoveAlong("historymarker", false); }, 5000);
        this._historyshowtimer = setTimeout(function() {
            myClass.showHistoryPointOnMap(myClass);
        }, 1000);
    },
    //    showHistoryPointOnMap: function(myClass) {
    //        if (myClass.historyshowindex < myClass.historyOverlayArray.length) {
    //            myClass.map.addOverlay(myClass.historyOverlayArray[myClass.historyshowindex], false);
    //            myClass.historyshowindex++;
    //            myClass.map.setOverlayToTopById("historymarker");
    //        }
    //    },
    showHistoryPointOnMap: function(myClass) {
        if (myClass.historyshowindex < myClass.trackerhistoryinfoArray.length) {
            var vinfo = this.trackerhistoryinfoArray[myClass.historyshowindex];

            var myId = 'historymarker-' + vinfo.gpstime;
            var pt = new MLngLat(vinfo.longitude, vinfo.latitude);
            pt = this.realLatLngToMapLatLng(pt);
            var WIN_HTML;
            var timetext = this._gpsTimeCap + ':' + vinfo.gpstime + '<BR/>';
            var speedtext = this._speedCap + ':' + vinfo.speed + 'km/h<BR/>';
            var otherinfo = "";
            if (vinfo.otherinfo)
                otherinfo = vinfo.otherinfo + '<BR/>';
            WIN_HTML = timetext + speedtext + otherinfo;
            if (vinfo.stopped)
                WIN_HTML += this._parkingTimeCap + ":" + vinfo.stoppedtime + '<BR/>';
            var mm;
            if (vinfo.stopped) {
                mm = this.createStoppedMarker(myId, pt, WIN_HTML);
            }
            else
                mm = this.createTrackMarker(myId, pt, vinfo.direction.toString(), WIN_HTML);
            this.historyOverlayArray.push(mm);
            //pts.push(pt);
            myClass.map.addOverlay(myClass.historyOverlayArray[myClass.historyshowindex], false);
            myClass.map.setOverlayToTopById("historymarker");
            myClass.historyshowindex++;
            if (!myClass._hidehistoryline) {
                historyLine.lnglatArr.push(pt);
                myClass.map.updateOverlay(historyLine);
            }
            myClass.map.setCenter(pt);
            this._historyshowtimer = setTimeout(function() {
                myClass.showHistoryPointOnMap(myClass);
            }, 1000);
        }
        else if (myClass.historyshowindex == myClass.trackerhistoryinfoArray.length) {
            if (myClass._historylineendfn != null)
                myClass._historylineendfn(myClass); //call back
        }
    },
    stopAnimate: function() {
        this.map.pauseMoveAlong("historymarker");
    },
    startAnimate: function() {
        this.map.startMoveAlong("historymarker", false);
    },
    speedUpAnimate: function() {
        this.animateinterval = this.animateinterval + 1;
        //加快速度
    },
    slowDownAnimate: function() {
        this.animateinterval = this.animateinterval - 1;
        //减慢速度
    },
    toStartPoint: function() {
        this.map.stopMoveAlong("historymarker");
        this.map.markerMoveTo("historymarker", this.theFirstHistoryPoint, 0, 5);
    },
    toEndPoint: function() {
        if (this.historyshowindex < this.historyOverlayArray.length - 1)
            this.historyshowindex = this.historyOverlayArray.length - 1;
        this.map.stopMoveAlong("historymarker");
        this.map.markerMoveTo("historymarker", this.theLastHistoryPoint, 0, 5);
    },
    getZoomFromRadius: function(accuracy) {
        if (accuracy < 2500)
            zoom = 15;
        else if (accuracy > 2500 && accuracy < 5000)
            zoom = 13;
        else
            zoom = 12;
        return zoom;
    },

    drawAlarmPoint: function(trackerinfo) {
        var pt = new MLngLat(trackerinfo.longitude, trackerinfo.latitude);
        if (trackerinfo.gsminfo != null)
            pt = new MLngLat(trackerinfo.gsminfo.longitude, trackerinfo.gsminfo.latitude);
        pt = this.realLatLngToMapLatLng(pt); //--trans latlng-
        var alarminfo = trackerinfo.alarminfo;
        var color = 0x000000;
        if (alarminfo.length > 0)
            color = 0xFF0000;
        var content = trackerinfo.devicename + ' ' + trackerinfo.speed + 'km/h' + ' ' + alarminfo + ' ' + trackerinfo.gpstime + ' ' + trackerinfo.address;
        var labelOption = new MLabelOptions();
        labelOption.hasBorder = true;
        labelOption.hasBackground = true;
        labelOption.labelPosition = new MPoint(16, -16);
        labelOption.alpha = 0.8;
        var fontstyle = new MFontStyle();
        fontstyle.color = color;
        labelOption.content = content;
        labelOption.fontStyle = fontstyle;
        var marker = this.createMABCMarker("alarm" + trackerinfo.deviceid, pt, labelOption, null, "images/caution.png", false);
        this.map.addOverlay(marker, true);
    },

    drawHistoryPoint: function(record) {
        var lati = record.get("latitude");
        var longi = record.get("longitude");
        var direction = record.get("direction");
        var hasgsmlocation = record.get("hasgsmlocation");
        var pt = new MLngLat(longi, lati);
        var circle = null;
        if (hasgsmlocation) {
            pt = new MLngLat(record.get("gsmlongitude"), record.get("gsmlatitude"));
        }
        pt = this.realLatLngToMapLatLng(pt); //--trans latlng-
        var mm;
        var zoom = 14;
        if (hasgsmlocation) {
            var accuracy = record.get("gsmaccuracy");
            circle = this.createCircle(pt, accuracy, '0x0000ff', false);
            mm = this.createMABCMarker(record.get("gpstime") + "-tracker", pt, null, null, "images/man.gif");
            zoom = this.getZoomFromRadius(accuracy);
            this.map.addOverlays([mm, circle], true);
        }
        else {
            mm = this.createTrackMarker(record.get("gpstime") + "-tracker", pt, direction);
            this.map.addOverlay(mm, true);
        }
    },
    drawParkingPoint: function(record) {
        var lati = record.get("Latitude");
        var longi = record.get("Longitude");
        var pt = new MLngLat(longi, lati);
        pt = this.realLatLngToMapLatLng(pt); //--trans latlng-
        var mm;
        var zoom = 14;
        mm = this.createTrackMarker("tracker", pt, 0);
        this.map.addOverlay(mm, true);
        this.map.setZoomAndCenter(zoom, pt);
    }
    , findLocation: function(lat, lng, latiCap, longiCap) {
        var point = new MLngLat(lng, lat);
        point = this.realLatLngToMapLatLng(point); //--trans latlng-
        this.removeFound();
        var WIN_HTML = latiCap + lat.toString() + "," + longiCap + lng.toString();
        var tipOption = new MTipOptions();
        tipOption.content = WIN_HTML;
        tipOption.hasShadow = true;
        tipOption.roundRectSize = 3;
        tipOption.contentFontStyle.size = 16;
        tipOption.contentFontStyle.bold = false;
        tipOption.tipType = MConstants.FLASH_BUBBLE_TIP;
        this.findOutLocationOverlay = this.createMABCMarker("findoutoverlay", point, null, tipOption, "images/red.png");
        this.map.addOverlay(this.findOutLocationOverlay, true);
    },
    removeFound: function() {
        if (this.findOutLocationOverlay != null) {
            this.map.removeOverlay(this.findOutLocationOverlay);
            this.findOutLocationOverlay = null;
        }
    },
    drawPOI: function(poiid, name, lat, lng, iconindex, centermap) {
        var pt = new MLngLat(lng, lat);
        var labelOption = new MLabelOptions();
        labelOption.hasBorder = true;
        labelOption.hasBackground = true;
        labelOption.labelPosition = new MPoint(0, -26);
        labelOption.alpha = 0.8;
        labelOption.content = name;
        var marker = this.createMABCMarker(poiid, pt, labelOption, null, "images/poi32.gif");
        this.poiOverlayArray.push(marker);
        this.map.addOverlay(marker, false);
    },
    beginAddPOI: function(submitcap, cancelcap) {
        this._submitcap = submitcap;
        this._cancelcap = cancelcap;
        this.cancelAddEditPOI();
        this.changeTool(MEnumMapToolType.AddPOI);
    },
    drawAddPOI: function(lat, lng, iconindex, submitcap, cancelcap) {
        var pt = new MLngLat(lng, lat);
        var realpt = this.mapLatLngToRealLatLng(pt);
        var WIN_HTML = '<div style="width: 12em; style: font-size: small"><INPUT id="textpoi" name="textpoi" value=""><INPUT id=butAddPOI type=button class="cornerbutton" value=';
        WIN_HTML += this._submitcap + ' name=submit onclick="return submitAddPOI(\'\',' + realpt.latY.toString() + ',' + realpt.lngX.toString() + ',' + iconindex + ')">&nbsp;<INPUT id=butCancel  class="cornerbutton" type=button value=';
        WIN_HTML += this._cancelcap + ' name=cancel onclick="cancelAddEditPOI()"></div>';
        if (this.addPOIOverlay) {
            this.map.removeOverlay(this.addPOIOverlay);
            this.addPOIOverlay = null;
        }
        else {
            var tipOption = new MTipOptions();
            tipOption.content = WIN_HTML;
            tipOption.tipType = MConstants.IMG_BUBBLE_TIP;
            this.addPOIOverlay = this.createMABCMarker("myaddpoi", realpt, null, tipOption, "images/poi32b.gif");
            this.map.addOverlay(this.addPOIOverlay, false);
        }
        this.changeTool(MEnumMapToolType.Pan);
    },
    beginEditMovePOI: function(poiid, lat, lng, iconindex, name, submitcap, cancelcap) {
        this._submitcap = submitcap;
        this._cancelcap = cancelcap;
        this._movepoiname = name;
        this._movepoiid = poiid;
        this.cancelAddEditPOI();
        this.changeTool(MEnumMapToolType.BeginEditMovePOI);
    },
    drawMovePOI: function(poiid, lat, lng, iconindex) {
        var pt = new MLngLat(lng, lat);
        var realpt = this.mapLatLngToRealLatLng(pt);
        var WIN_HTML = '<div style="width: 12em; style: font-size: small"><INPUT id="textpoi" name="textpoi" value="' + this._movepoiname + '"><INPUT id=butAddPOI type=button value=';
        WIN_HTML += this._submitcap + ' name=submit class="cornerbutton" onclick="return submitEditPOI(' + this._movepoiid + ',\'' + this._movepoiname + '\',' + realpt.latY.toString() + ',' + realpt.lngX.toString() + ',' + iconindex + ')">&nbsp;<INPUT id=butCancel type=button value=';
        WIN_HTML += this._cancelcap + ' name=cancel class="cornerbutton" onclick="cancelAddEditPOI()"></div>';
        var tipOption = new MTipOptions();
        tipOption.content = WIN_HTML;
        tipOption.tipType = MConstants.IMG_BUBBLE_TIP;
        if (this.movePOIOverlay) {
            this.map.removeOverlay(this.movePOIOverlay);
            this.movePOIOverlay = null;
        }
        this.movePOIOverlay = this.createMABCMarker("mymovepoi", pt, null, tipOption, "images/poi32b.gif");
        this.map.addOverlay(this.movePOIOverlay, false);
    },
    cancelAddEditPOI: function() {
        this.map.closeTip();
        if (this.addPOIOverlay) {
            this.map.removeOverlay(this.addPOIOverlay);
            this.addPOIOverlay = null;
        }
        if (this.movePOIOverlay) {
            this.map.removeOverlay(this.movePOIOverlay);
            this.movePOIOverlay = null;
        }
        this.changeTool(MEnumMapToolType.Pan);
    },
    drawPOIbyRecords: function(records) {
        this.hidePOI();
        var i = 0;
        for (i = 0; i < records.length; i++) {
            var record = records[i];
            var lat = record.get("latitude");
            var lng = record.get("longitude");
            var name = record.get("poiname");
            var poiid = record.get("poiid");
            var iconindex = record.get("iconindex");
            this.drawPOI(poiid, name, lat, lng, iconindex, false);
        }
    },

    hidePOI: function() {
        this.map.removeOverlays(this.poiOverlayArray);
    }

     , removeFromMap: function(ids) {
         //函数未完成
     }

    , distanceFrom: function(lnglat1, lnglat2) {
        var lat = [lnglat1.latY, lnglat2.latY];
        var lng = [lnglat1.lngX, lnglat2.lngX]; //var R = 6371; // km (change this constant to get miles)
        var R = 6378137; // In meters
        var dLat = (lat[1] - lat[0]) * Math.PI / 180;
        var dLng = (lng[1] - lng[0]) * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat[0] * Math.PI / 180) * Math.cos(lat[1] * Math.PI / 180) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c;
        return Math.round(d);
    },

    realtimeTracking: function(record, gpsTimeCap, speedCap) {
        var tinfo = this.translateRecordToTrackerInfo(record);
        if (tinfo) {
            var pt = new MLngLat(tinfo.longitude, tinfo.latitude);
            pt = this.realLatLngToMapLatLng(pt); //--trans latlng-
            var isGPSFlowingPoint = false; //is the point is gps flowing point
            if (this.realtimeTrackingLine == null) {
                this.realtimeTrackingLine = this.createMABCPolyLine("realtimepolyline", [pt, pt], MConstants.LINE_DASHED, 0x005cb5, false);
                this.map.addOverlay(this.realtimeTrackingLine, false);
            }
            else {
                var lnglatArr = this.realtimeTrackingLine.lnglatArr;
                var lastpt = lnglatArr[lnglatArr.length - 1];
                lnglatArr.push(pt);
                this.map.updateOverlay(this.realtimeTrackingLine);
            }
            if (!isGPSFlowingPoint) {
                tinfo.direction = (tinfo.direction != null ? tinfo.direction : "0");
                var WIN_HTML;
                var timetext = gpsTimeCap + ':' + tinfo.gpstime + '<BR/>';
                var speedtext = speedCap + ':' + tinfo.speed + 'km/h<BR/>';
                WIN_HTML = timetext + speedtext;
                var marker = this.createTrackMarker(tinfo.deviceid + tinfo.gpstime, pt, tinfo.direction, WIN_HTML);
                var myClass = this;
                this.map.addEventListener(marker, MConstants.MOUSE_OVER, function(params) {
                    myClass.map.openOverlayTip(marker.id);
                });
                if (this.realtimeOverlayArray.length < 15) {
                    this.map.addOverlay(marker, false);
                    this.realtimeOverlayArray.push(marker);
                }
                else {
                    this.map.addOverlay.removeOverlay(this.realtimeOverlayArray[0]);
                    this.realtimeOverlayArray.remove(this.realtimeOverlayArray[0]);
                    this.map.addOverlay(marker, false);
                    this.realtimeOverlayArray.push(marker);
                }
            }
            else {
                var marker = this.realtimeOverlayArray[this.realtimeOverlayArray.length - 1];
                marker.lnglat = pt;
                this.map.updateOverlay(marker);
            }
            this.map.panTo(pt);
        }
    },
    setRouteCap: function(okCap, cancelCap, farCap, closeCap, allOkCap) {
        this._submitAddRouteCap = okCap;
        this._submitAddAllRouteCap = allOkCap;
        this._cancelAddRouteCap = cancelCap;
        this._farCap = farCap;
        this._closeCap = closeCap;
    },
    drawRouteLine: function() {
        this.changeTool(MEnumMapToolType.DrawDefinedRouteLine);
        this._isEditMode = true;
    },
    showOneEditRoute: function(sssid, points) {
        this._isEditMode = true;
        this._editRouteID = sssid;
        var pArray = points.split(',');
        var mPoints = new Array();
        var sMarker, eMarker;
        var poly = this.createMABCPolyLine("my_defined_simple_route", mPoints, MConstants.LINE_SOLID, 0x005cb5, true);
        this.complecateDefinedRoute = poly;
        for (var i = 0; i < pArray.length; i += 2) {
            var point = this.realLatLngToMapLatLng(new MLngLat(pArray[i], pArray[i + 1]));
            mPoints.push(point);
            if (i == 0)
                sMarker = this.createDefinedRouteStepMarker("my_defined_route_point_0", point, null, null, "images/mm_20_white.png", true);
            else if (i == pArray.length - 2)
                eMarker = this.createDefinedRouteStepMarker("my_defined_route_point_1", point, null, null, "images/mm_20_white.png", true);
        }
        this.map.addOverlays([sMarker, eMarker, poly], true);
        this.allDefinedRoutePoint.push(sMarker);
        this.allDefinedRoutePoint.push(eMarker);
    },
    clearRoute: function() {
        this.map.removeOverlays(this.allDefinedRoutePoint);
        this.map.removeOverlay(this.simpleDefinedRoute);
        this.map.removeOverlay(this.complecateDefinedRoute);
        //        this.map.removeOverlays([this.simpleDefinedRoute, this.complecateDefinedRoute]);
        this.allDefinedRoutePoint = [];
        this.simpleDefinedRoute = null;
        this.complecateDefinedRoute = null;
        this._isEditMode = false;
    },
    routeSearch: function(per, routeType) {
        var arr = new Array();
        for (var i = 0; i < this.allDefinedRoutePoint.length; i++) {
            arr.push(this.allDefinedRoutePoint[i].lnglat);
        }
        var multiXY = new MLngLats(arr);
        var mrs = new MRouteSearch();
        var opt = new MRouteSearchOptions();
        opt.per = per; //抽吸函数，表示在地图上画导航路径的关键点的个数,默认为150
        opt.routeType = routeType; //路径计算规则,0表示速度优先（默认）
        var myClass = this;
        mrs.setCallbackFunction(function(data) {
            if (myClass.complecateDefinedRoute != null) {
                myClass.map.removeOverlay(myClass.complecateDefinedRoute);
            }
            if (myClass.simpleDefinedRoute != null) {
                myClass.map.removeOverlay(myClass.simpleDefinedRoute);
            }
            if (data.error_message != null) {
                myClass.map.addOverlay(myClass.simpleDefinedRoute, false);
            }
            else {
                switch (data.message) {
                    case 'ok':
                        var route_count = data.count;
                        if (route_count == 0) {

                        }
                        else {
                            var route_segment = new Array();
                            for (var i = 0; i < route_count; i++) {
                                route_segment[i] = data.segmengList[i].coor; //每一条路线的XY 
                            }
                            var allover = new Array();
                            var arr = new Array();
                            var poi_xy_r = data.coors.split(",");
                            var poi_xy_rl = poi_xy_r.length - 2
                            for (var j = 0; j < poi_xy_rl; j = j + 2) {
                                if (j == 0) {
                                    arr.push(myClass.allDefinedRoutePoint[0].lnglat);
                                }
                                arr.push(new MLngLat(poi_xy_r[j], poi_xy_r[j + 1]));
                                if (j == poi_xy_rl - 1) {
                                    arr.push(myClass.allDefinedRoutePoint[1].lnglat);
                                }
                            }
                            var line = myClass.createMABCPolyLine("my_defined_route_line", arr, MConstants.LINE_SOLID, 0x005cb5, true);
                            allover.push(line);
                            myClass.map.addOverlays(allover, true);
                            myClass.complecateDefinedRoute = line;
                        }
                        break;
                    case 'error':
                        break;
                    default:
                        break;
                }
            }
        });
        mrs.routeSearchByMultiPoi(multiXY, opt);
    },
    clearDirection: function() {
        if (this.mySearchRouteOverlay.length > 0) {
            this.map.removeOverlays(this.mySearchRouteOverlay);
        }
    },
    findRoute: function(startName, endName, startX, startY, endX, endY, panel) {
        function Getdistance(le) {
            if (le <= 1000) {
                var s = le;
                return s + "米";
            } else {
                var s = Math.round(le / 1000);
                return "约" + s + "公里";
            }
        }



        var startXY = new MLngLat(startX, startY);
        var endXY = new MLngLat(endX, endY);
        var mls = new MRouteSearch();
        var resultStr = "";
        var opt = new MRouteSearchOptions();
        opt.per = 1500;
        opt.routeType = 0;
        opt.name = "";
        var regionL = "";
        var resultArr = null;
        var myClass = this;
        mls.setCallbackFunction(function(data) {
            if (data.error_message != null) {
            }
            else {
                switch (data.message) {
                    case 'ok':
                        var route_count = data.count;
                        if (route_count == 0) {
                        }
                        else {
                            var route_text = ""; var road_length = 0;
                            var route_content = new Array();
                            var route_segment = new Array();
                            resultArr = data.segmengList;
                            for (var i = 0; i < route_count; i++) {
                                route_segment[i] = data.segmengList[i].coor;
                                road_length += parseInt(data.segmengList[i].roadLength);
                                if (i == 0) {
                                    route_text += "<tr class=\"td_style\" id=\"tr_" + i + "\" onMouseover=\"this.style.backgroundColor='#efefef';\" onMouseout=\"this.style.backgroundColor='';\" ><td align=\"center\">" + (i + 1) + ".</td><td width=\"177\">沿<strong>" + data.segmengList[i].roadName + "</strong>向<strong>" + data.segmengList[i].direction + "</strong><span class=\"gray\">行驶</span></td><td align=\"right\">" + Getdistance(data.segmengList[i].roadLength) + "</td><td>&nbsp;</td></tr>";
                                } else {
                                    route_text += "<tr class=\"td_style\" id=\"tr_" + i + "\" onMouseover=\"this.style.backgroundColor='#efefef';\" onMouseout=\"this.style.backgroundColor='';\" ><td align=\"center\">" + (i + 1) + ".</td><td width=\"177\">" + data.segmengList[i - 1].action + "<span class=\"gray\">进入</span><strong>" + data.segmengList[i].roadName + "</strong>向<strong>" + data.segmengList[i].direction + "</strong><span class=\"gray\">行驶</span></td><td align=\"right\">" + Getdistance(data.segmengList[i].roadLength) + "</td><td>&nbsp;</td></tr>";
                                }
                            }
                            route_content.push("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"inner_route_result\"><tr><td colspan=\"2\" style=\"background:#e1e1e1;\" width=\"60%\">路线</td><td width=\"38%\" align=\"right\" style=\" border-left:1px solid #fff; background:#e1e1e1;\">里程</td><td width=\"2%\"  style=\"background:#e1e1e1;\">&nbsp;</td> </tr><tr><td width=\"3\" align=\"center\"><img src=\"http://code.mapabc.com/images/start.gif\" /></td><td colspan=\"2\">起点：" + startName + "</td><td width=\"17\">&nbsp;</td></tr>" + route_text + "<tr><td align=\"center\"><img src=\"http://code.mapabc.com/images/end.gif\" /></td><td colspan=\"2\">终点：" + endName + "</td></tr><tr><td colspan=\"3\" align=\"right\">共：" + Getdistance(road_length) + "</td></tr></table>");
                            resultStr = route_content.join("");
                            var arr = new Array();
                            var poi_xy_r = data.coors.split(",");
                            var poi_xy_rl = poi_xy_r.length - 2
                            var startPoint, endPoint;
                            for (var j = 0; j < poi_xy_rl; j = j + 2) {
                                if (j == 0) {
                                    startPoint = new MLngLat(poi_xy_r[j], poi_xy_r[j + 1]);
                                }
                                arr.push(new MLngLat(poi_xy_r[j], poi_xy_r[j + 1]));
                                if (j == poi_xy_rl - 1) {
                                    endPoint = new MLngLat(poi_xy_r[j], poi_xy_r[j + 1]);
                                }
                            }
                            var startMarker = myClass.createMABCMarker("start_find_route_marker", startPoint, null, null, "images/qd.png", false);
                            var endMarker = myClass.createMABCMarker("end_find_route_marker", endPoint, null, null, "images/zd.png", false);
                            var line = myClass.createMABCPolyLine("my_defined_route_line", arr, MConstants.LINE_SOLID, 0x005cb5, false);
                            myClass.mySearchRouteOverlay = [line, startMarker, endMarker];
                            myClass.map.addOverlays(myClass.mySearchRouteOverlay, true);
                            panel.innerHTML = "<div>" + resultStr + "</div>";
                        }
                        break;
                    case 'error':
                        break;
                    default:
                        break;
                }
            }
        });
        mls.routeSearchByTwoPoi(startXY, endXY, opt);
    },
    getDefaultImageUrl: function(trackerinfo) {
        var s = trackerinfo.devicetype;
        var direction = parseFloat(trackerinfo.direction);
        var url = "blue.gif";

        if (s == 0 || s == 1 || s == 2 || s == 5 || s == 7 || s == 12) {
            url = "man.gif";
        }
        else {
            var baseImagePath;
            if (trackerinfo.gsminfo != null) {
                url = "car.gif";
            }
            else {
                baseImagePath = "car_";
                if (direction >= 337.5 || direction < 22.5)
                    url = baseImagePath + "n.png";
                else if (direction >= 22.5 && direction < 67.5)
                    url = baseImagePath + "ne.png";
                else if (direction >= 67.5 && direction < 112.5)
                    url = baseImagePath + "e.png";
                else if (direction >= 112.5 && direction < 157.5)
                    url = baseImagePath + "se.png";
                else if (direction >= 157.5 && direction < 202.5)
                    url = baseImagePath + "s.png";
                else if (direction >= 202.5 && direction < 247.5)
                    url = baseImagePath + "sw.png";
                else if (direction >= 247.5 && direction < 292.5)
                    url = baseImagePath + "w.png";
                else if (direction >= 292.5 && direction < 337.5)
                    url = baseImagePath + "nw.png";
            }
        }
        return url;
    }

}



